import os
import pandas as pd
import json
from modules.storage.enums import CSV, JSON, TXT


# 文件保存不继承StorageBase
# 文件保存包含三种文件类型：txt,csv,json

class FileStore:
    def __init__(self, file_path, read_file_mode='r', write_file_mode='wb'):
        """
        初始化 FileStore 实例

        Parameters:
        - file_path (str): 文件路径
        - read_file_mode (str): 读取文件时的模式，默认为 'r'
        - write_file_mode (str): 写入文件时的模式，默认为 'wb'
        """
        self.file_path = file_path
        self.read_file_mode = read_file_mode
        self.write_file_mode = write_file_mode
        self.file_type = os.path.splitext(file_path)[1][1:]

    def read(self):
        """
        读取文件内容

        Returns:
        - result: 读取到的文件内容，根据文件类型可能是列表、字典等
        """
        try:
            if self.file_type == CSV:
                df = pd.read_csv(self.file_path)
                result = df.values.tolist()
            elif self.file_type == JSON:
                with open(self.file_path, encoding='utf-8') as file:
                    result = json.load(file)
            else:
                with open(self.file_path, mode=self.read_file_mode, encoding='utf-8') as file:
                    result = file.read()
            return result
        except Exception as e:
            print(f"读取文件时发生错误: {e}")
            return None

    def write(self, file_data):
        try:
            if self.file_type == CSV:
                self.write_csv(file_data)
            elif self.file_type == JSON:
                self.write_json(file_data)
            elif self.file_type == TXT:
                self.write_txt(file_data)
            elif isinstance(file_data, bytes):
                self.write_bytes(file_data)
            elif isinstance(file_data, str):
                self.write_str(file_data)
            elif hasattr(file_data, '__iter__') and not isinstance(file_data, (str, bytes, dict, list)):
                self.write_stream(file_data)
            else:
                print("Unsupported data type for the specified file type.")
        except Exception as e:
            print(f"An error occurred while writing to the file: {e}")

    def write_csv(self, file_data):
        """写入CSV文件"""
        if isinstance(file_data, dict):
            df = pd.DataFrame.from_records([file_data])
        elif isinstance(file_data, list):
            df = pd.DataFrame(file_data)
        else:
            raise ValueError("CSV文件数据必须是字典或列表类型")
        df.to_csv(self.file_path, index=False)

    def write_json(self, file_data):
        """写入JSON文件"""
        if not isinstance(file_data, (dict, list)):
            raise ValueError("JSON文件数据必须是字典或列表类型")
        with open(self.file_path, 'w', encoding='utf-8') as file:
            json.dump(file_data, file, indent=2, ensure_ascii=False)

    def write_txt(self, file_data):
        """写入TXT文件"""
        with open(self.file_path, 'w', encoding='utf-8') as file:
            if isinstance(file_data, dict):
                for key, value in file_data.items():
                    file.write(f"{key}:{value}\n")
            elif isinstance(file_data, str):
                file.write(file_data + '\n')

    def write_bytes(self, file_data):
        """写入二进制数据"""
        with open(self.file_path, 'wb') as file:
            file.write(file_data)

    def write_str(self, file_data):
        """写入字符串数据"""
        with open(self.file_path, 'w', encoding='utf-8') as file:
            file.write(file_data)

    def write_stream(self, file_data):
        """写入流数据，通常是响应流"""
        if not hasattr(file_data, '__iter__'):
            raise ValueError("流数据必须是可迭代的字节序列")
        with open(self.file_path, 'wb') as file:
            for chunk in file_data.iter_content(chunk_size=1024):
                if chunk:
                    file.write(chunk)





if __name__ == "__main__":
    file = FileStore('data.txt')
    data = {
        'name': 'joe',
        'key': 'great'
    }
    file.write(data)
    # file.read()
